#include "ObserverSituationInterface.hpp"

#include "GenSocketManager.hpp"
#include "GenUDP_Connection.hpp"

#include "observer/WsfSimulationObserver.hpp"

ObserverSituationInterface::ObserverSituationInterface(UtCallbackHolder &callBackes, GenUDP_Connection *conn)
	: mConnectionPtr(conn)
{
	callBackes.Add(WsfObserver::AdvanceTime(&GetSimulation()).Connect(&ObserverSituationInterface::AdvanceTime, this)); // 时间推进事件
}

void ObserverSituationInterface::AdvanceTime(double aSimTime)
{
	// 检查是否到达整秒
	static double lastSecond = 0.0;
	int currentSecond = static_cast<int>(aSimTime);

	if (currentSecond > lastSecond)
	{
		lastSecond = currentSecond;

		// 生成态势数据
		Json::Value simulationData = GenerateSimulationData(aSimTime);

		// 转换为JSON字符串
		Json::FastWriter writer;
		std::string jsonData = writer.write(simulationData);

		// 发送数据
		SendPacket(jsonData);
	}
}

void ObserverSituationInterface::SendPacket(const std::string &aMessage)
{
	int bytesWritten = mConnectionPtr->SendBuffer(aMessage.c_str(), aMessage.length() + 1);
	if (bytesWritten < 0)
	{
		//ut::log::error() << "Socket error: " << GenSockets::GenSocketManager::GetLastError();
	}
}

Json::Value ObserverSituationInterface::GenerateSimulationData(double aSimTime)
{
	Json::Value simulationData;

	Json::Value simulationTime;
	double startTime = GetSimulation().GetDateTime().GetStartTime();
	double currentTime = GetSimulation().GetSimTime();
	double stepTime = GetSimulation().GetTimestep();
	simulationTime["BeginTime"] = startTime;
	simulationTime["CurrentTime"] = currentTime;
	simulationTime["CurrentStep"] = stepTime;
	simulationData["SimulationTime"] = simulationTime;

	Json::Value simulationSide;
	std::map<std::string, Json::Value> sideMap;
	for (const auto& platformInfo : mPlatformSides)
	{
		std::string side = platformInfo.side;
		int index = platformInfo.index;

		// 如果该阵营尚未处理，则创建新的SimSide结构
		if (sideMap.find(side) == sideMap.end())
		{
			Json::Value simSide;
			simSide["ID"] = side; // 使用阵营名称作为ID
			simSide["Name"] = side; // 阵营名称
			simSide["Postures"] = Json::Value(Json::objectValue); // 空对象，无法获取对立关系
			simSide["CombatUnits"] = Json::Value(Json::arrayValue); // 作战单元数组
			simSide["Contacts"] = Json::Value(Json::arrayValue); // 探测单元数组（保持为空）
			simSide["CombatAreas"] = Json::Value(Json::arrayValue); // 空数组，非必填
			simSide["AreaPoints"] = Json::Value(Json::arrayValue); // 空数组，非必填

			sideMap[side] = simSide;
		}

		WsfPlatform* platform = GetSimulation().GetPlatformByIndex(index);
		if (!platform)
			continue;

		Json::Value combatUnit = CreateCombatUnit(platform);
		sideMap[side]["CombatUnits"].append(combatUnit);
	}

	for (auto& sidePair : sideMap)
	{
		simulationSide.append(sidePair.second);
	}

	simulationData["SimulationSide"] = simulationSide;
	return simulationData;
}
